/**
 * Created by 86185 in 2020/8/15 on 16:46
 */
const path = require("path");
const express = require("express");

import log4js from "@/util/log.util"
import ReadFileUtil from "@/util/readFile.util"
import parseUrlParamsFilter from "@/filter/parseUrlParams.filter"

const logger = log4js.getLogger("default");

class MiddlewareRouter {
    constructor(app, config) {
        this.app = app;
        this.createRoute(config);
    }

    createRoute(config) {

        let staticPath = config.frontendDir || path.join(process.cwd(), "frontend/public");

        logger.info(`开启静态资源服务：${staticPath} -> ${config.contextPath}`);

        this.app.use(`${config.contextPath}`, express.static(staticPath));

        this.app.get(`${config.contextPath}/config`, (req, res) => {

            res.send({
                appName: config.appName,
                contextPath: config.contextPath,
                userName: config.userName,
                userId: config.userId,
            })

        });

        this.app.get(`${config.contextPath}/province/single`, (req, res) => {

            let paramsObj = parseUrlParamsFilter(req.url);

            let file = new ReadFileUtil(`${paramsObj["adcode"]}.json`).readFile();
            if (file) {
                res.send({
                    status: 200,
                    data: file,
                    message: "success"
                })
            } else {
                res.send({
                    status: 500,
                    data: "文件读取错误",
                    message: "error"
                })
            }
        })

    }
}

export default MiddlewareRouter
